package com.qkun.library.utils;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.qkun.library.base.BaseApplication;

/**
 * @author qinkun
 * @date 11/21 0021 19:35
 * @description 传感器是非常耗电的，在不用时一定要释放
 */
public abstract class BaseSensorEventListener implements SensorEventListener {

    private final SensorManager mSensorManager;

    public BaseSensorEventListener() {
        mSensorManager = (SensorManager) BaseApplication.getAppContext().getSystemService(Context.SENSOR_SERVICE);
    }

    public SensorManager getSensorManager() {
        return mSensorManager;
    }

    /**
     * @param sensorType
     * @param samplingPeriodUs 延迟时间的精密度
     */
    public boolean register(int sensorType, int samplingPeriodUs) {
        if (Utils.nonNull(mSensorManager)) {
            return register(mSensorManager.getDefaultSensor(sensorType), samplingPeriodUs);
        }
        return false;
    }

    /**
     * @param sensor
     * @param samplingPeriodUs 延迟时间的精密度
     */
    public boolean register(Sensor sensor, int samplingPeriodUs) {
        if (Utils.nonNull(mSensorManager) && Utils.nonNull(sensor)) {
            mSensorManager.registerListener(this, sensor, samplingPeriodUs);
            return true;
        }
        return false;
    }

    public boolean unregister(int sensorType) {
        if (Utils.nonNull(mSensorManager)) {
            return unregister(mSensorManager.getDefaultSensor(sensorType));
        }
        return false;
    }

    public boolean unregister(Sensor sensor) {
        if (Utils.nonNull(mSensorManager)) {
            mSensorManager.unregisterListener(this, sensor);
            return true;
        }
        return false;
    }

    /**
     * 传感器报告新的值
     *
     * @param event
     */
    @Override
    public abstract void onSensorChanged(SensorEvent event);

    /**
     * 传感器精度发生变化
     *
     * @param sensor
     * @param accuracy {@link SensorManager#SENSOR_STATUS_UNRELIABLE}
     *                 {@link SensorManager#SENSOR_STATUS_ACCURACY_LOW}
     *                 {@link SensorManager#SENSOR_STATUS_ACCURACY_MEDIUM}
     *                 {@link SensorManager#SENSOR_STATUS_ACCURACY_HIGH}
     */
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}
